package dyyx.echo;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.traffic.ChannelTrafficShapingHandler;
import io.netty.util.concurrent.DefaultThreadFactory;

public class EchoServerInit extends ChannelInitializer<SocketChannel> {
	
	/*
	private static final ThreadFactory threadFactory = new ThreadFactoryBuilder()
            .setNameFormat("netty-context-business-%d")
            .setDaemon(false)
            .build();
            */
	
    // private static final NioEventLoopGroup biz = new NioEventLoopGroup(200,threadFactory);
    private static final NioEventLoopGroup bizGroup = new NioEventLoopGroup(EchoServer.bizThreads,new DefaultThreadFactory("bizGroup"));

    private static final TraficCountHandler traficCountHandler = new TraficCountHandler();

    @Override
    public void initChannel(SocketChannel ch) {
    	System.out.println("\n*********initChannel run,"+ch+"\n\n");
    	
    	// 连接建立后 initChannel ，添加 handler ， 每一个 handler 都会创建一个 ChannelHandlerContext

        ChannelPipeline pipeline = ch.pipeline();
        // INFO debug
        // pipeline.addLast("logging", new LoggingHandler(LogLevel.INFO));
        // ch.pipeline().addLast("channelTrafficShaping", new ChannelTrafficShapingHandler(1024 * 1024, 1024 * 1024, 1000));
        
        ch.pipeline().addLast("traficCountHandler", traficCountHandler);
        
        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));  
        pipeline.addLast("decoder", new StringDecoder());  
        pipeline.addLast("encoder", new StringEncoder()); 
        
        // ChannelPipeline addLast(EventExecutorGroup group, ChannelHandler... handlers)
         
        // pipeline.addLast(new EchoServerHandler());
        // 
        // pipeline.addLast(bizGroup,new EchoServerHandler());
        
        if(EchoServer.TYPE_bizThreadPool.equals(EchoServer.type)){
            pipeline.addLast(new EchoServerHandlerUseThreadPool());
            System.out.println("use bizThreadPool");
        }else if(EchoServer.TYPE_bizEventLoopGroup.equals(EchoServer.type)){
        	pipeline.addLast(bizGroup,new EchoServerHandler());
            System.out.println("use bizEventLoopGroup");
        }else{
        	pipeline.addLast(new EchoServerHandler());
            System.out.println("no bizEventLoopGroup and bizThreadPool");
        }

        
    }
	
}
